package com.adcc.monitoragent.util;

import org.codehaus.jackson.annotate.JsonTypeInfo;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
/**
 * json串输出
 * @author charlie
 *
 */
public class JsonUtil {
	private final static Logger log = LoggerFactory.getLogger(JsonUtil.class);
	public static ObjectMapper mapper = new ObjectMapper();
	static {
		  mapper.enableDefaultTyping(); // defaults for defaults (see below); include as wrapper-array, non-concrete types
		  mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_OBJECT);
	}
	
	/**
	 * 实体bean转换成json串
	 * @param bean
	 * @return
	 */
	public static String beanToJson(Object bean) {
		String json = null;
		try {
			json = mapper.writeValueAsString(bean);
		} catch (Exception e) {
			log.error("beanToJson转换失败:" + e.getMessage());
			e.printStackTrace();
		}
		return bean.getClass().getName() + " " + json;
	}
	
	/**
	 * json转换成监控bean
	 * @param json
	 * @return
	 */
	public static Object jsonToBean(String json) {
		Object bean = null;
		try {
			if(json != null && !"".equals(json)) {
				String className = json.split(" ")[0];
				json = json.replaceFirst(className, "").trim();
				bean = mapper.readValue(json, Class.forName(className));
			}
		} catch (Exception e) {
			log.error("jsonToBean转换失败:" + e.getMessage());
			e.printStackTrace();
		}
		return bean;
	}
	
	public static void main(String[] args) {
		
	}
}
